package leetcode.lt100;

class Solution_59 {
	public int[][] generateMatrix(int n) {
		int[][] matrix = new int[n][n];
		if (n == 0)
			return matrix;

		// 记录当前方向,0,1,2,3表示向右,向下,向左,向上
		int direction = 0;
		// 记录每个方向前进次数.0,1,2,3记录右,下,左,上
		int[] counter = new int[4];

		loop(matrix, direction, counter, 0, 0, 1);
		return matrix;
	}

	private void loop(int[][] matrix, int direction, int[] counter, int i, int j, int count) {
		matrix[i][j] = count;
		// 螺旋完毕
		if (count == matrix.length * matrix[0].length) {
			return;
		}
		// 先检测当前方向,再查看是否需要转向
		switch (direction) {
		// 向右
		case 0:
			// 需要转向了
			if (j + 1 + counter[1] == matrix[0].length) {
				counter[0] += 1;
				direction = 1;
				loop(matrix, direction, counter, i + 1, j, count + 1);
				return;
			}
			// 不需要转向
			loop(matrix, direction, counter, i, j + 1, count + 1);
			break;
		// 向下
		case 1:
			// 需要转向了
			if (i + 1 + counter[2] == matrix.length) {
				counter[1] += 1;
				direction = 2;
				loop(matrix, direction, counter, i, j - 1, count + 1);
				return;
			}
			// 不需要转向
			loop(matrix, direction, counter, i + 1, j, count + 1);
			break;
		// 向左
		case 2:
			// 需要转向了
			if (j == counter[3]) {
				counter[2] += 1;
				direction = 3;
				loop(matrix, direction, counter, i - 1, j, count + 1);
				return;
			}
			// 不需要转向
			loop(matrix, direction, counter, i, j - 1, count + 1);
			break;
		// 向上
		case 3:
			// 需要转向了
			if (i == counter[0]) {
				counter[3] += 1;
				direction = 0;
				loop(matrix, direction, counter, i, j + 1, count + 1);
				return;
			}
			// 不需要转向
			loop(matrix, direction, counter, i - 1, j, count + 1);
			break;
		}
	}
}
